//
//  UIApplication+BKExt.swift
//  TestDemoSwift
//
//  Created by 王锦发 on 2020/3/31.
//  Copyright © 2020 WJF. All rights reserved.
//

import UIKit
import Foundation

var VisibleCtrl: UIViewController? {
    return UIApplication.topMostViewController()
}

var VisibleNaviCtrl: UINavigationController? {
    return UIApplication.topMostViewController()?.navigationController
}

// MARK: - UIApplication扩展
extension UIApplication {
    
    // 默认情况下keyWindow和delegate.window是同一个对象.但是当有系统弹窗出现的时候,keyWindow就变成了另外一个对象.
    // 建议将自定义view add到delegate.window而不是keyWindow上.
    func mainWindow() -> UIWindow? {
        if #available(iOS 13.0, *) {
            if let window = delegate?.window {
                return window
            } else if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
                      let keyWindow = windowScene.windows.first(where: { $0.isKeyWindow }) {
                return keyWindow
            } else {
                return nil
            }
        } else {
            return delegate?.window ?? keyWindow
        }
    }
    
    static func topMostViewController() -> UIViewController? {
        guard let window = UIApplication.shared.delegate?.window,
              let rootViewController = window?.rootViewController else {
            return nil
        }
        
        var topViewController: UIViewController? = rootViewController
        var visitedViewControllers: Set<UIViewController> = []
        
        while true {
            // 防止死循环
            if visitedViewControllers.contains(topViewController!) {
                break
            }
            visitedViewControllers.insert(topViewController!)
            
            if let presentedViewController = topViewController?.presentedViewController {
                topViewController = presentedViewController
            } else if let presentingViewController = topViewController?.presentingViewController {
                topViewController = presentingViewController
            } else if let navigationController = topViewController as? UINavigationController {
                topViewController = navigationController.topViewController
            } else if let tabBarController = topViewController as? UITabBarController {
                topViewController = tabBarController.selectedViewController
            } else {
                break
            }
        }
        
        return topViewController
    }
    
}
